package com.lingxu.module.homeIndex.service.impl;

import cn.hutool.system.oshi.CpuInfo;
import cn.hutool.system.oshi.OshiUtil;
import com.lingxu.base.common.api.vo.Result;
import com.lingxu.base.common.util.EasyExcelUtils;
import com.lingxu.base.config.MySessionListener;
import com.lingxu.module.homeIndex.entity.ModelData;
import com.lingxu.module.homeIndex.entity.ModelIDS;
import com.lingxu.module.homeIndex.entity.NumTypeVO;
import com.lingxu.module.homeIndex.entity.ParamsDTO;
import com.lingxu.module.homeIndex.mapper.HomeIndexMapper;
import com.lingxu.module.homeIndex.service.HomeIndexService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import oshi.SystemInfo;
import oshi.hardware.GlobalMemory;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.text.DecimalFormat;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @Title: HomeIndexServiceImpl
 * @Package: com.lingxu.module.homeIndex.service.impl
 * @Author: ysj闫世杰
 * @Email: 1105324813@qq.com
 * @Date: Created in 2023/6/27 11:27
 * @Description: 首页统计
 * @Version: 1.0.0
 */
@Service
public class HomeIndexServiceImpl implements HomeIndexService {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private HomeIndexMapper homeIndexMapper;


    /**
     * @Author ysj闫世杰
     * @Description 查询在线人数
     * @Date 2023/6/27 11:45
     * @Param:
     * @return com.lingxu.base.common.api.vo.Result
     **/
    @Override
    public Result findOnlineCount() {
        try {
            AtomicInteger userCount = MySessionListener.userCount;
            return Result.ok(userCount,"查询成功");
        }catch (Exception e){
            logger.error("数据查询异常",e);
            return Result.error("查询异常");
        }
    }

    /**
     * @Author ysj闫世杰
     * @Description 登录总次数
     * @Date 2023/6/27 16:37
     * @Param:
     * @return com.lingxu.base.common.api.vo.Result
     **/
    @Override
    public Result findLoginCount() {
        try {
            return Result.ok(homeIndexMapper.findLoginCount(),"查询成功");
        }catch (Exception e){
            logger.error("数据查询异常",e);
            return Result.error("查询异常");
        }
    }

    /**
     * @Author ysj闫世杰
     * @Description 模型类型分布
     * @Date 2023/6/27 16:41
     * @Param:
     * @return com.lingxu.base.common.api.vo.Result
     **/
    @Override
    public Result findModelTypeCount(ParamsDTO dto) {
        try {
            if("320800".equals(dto.getAreaCode())){
                dto.setAreaCode(null);
            }
            List<NumTypeVO> data = homeIndexMapper.findModelTypeCount(dto);
            return Result.ok(data,"查询成功");
        }catch (Exception e){
            logger.error("数据查询异常",e);
            return Result.error("查询异常");
        }
    }

    /**
     * @Author ysj闫世杰
     * @Description 查询系统使用情况
     * @Date 2023/6/27 17:49
     * @Param:
     * @return com.lingxu.base.common.api.vo.Result
     **/
    @Override
    public Result findUserAndUseCount() {
        try {
            return Result.ok(homeIndexMapper.findUserAndUseCount(),"查询成功");
        }catch (Exception e){
            logger.error("数据查询异常",e);
            return Result.error("查询异常");
        }
    }

    /**
     * @Author ysj闫世杰
     * @Description 查询模型排行·
     * @Date 2023/6/27 18:11
     * @Param:
     * @return com.lingxu.base.common.api.vo.Result
     **/
    @Override
    public Result rankByBrowseTimes() {
        try {
            List<Map<String, Object>> pt = homeIndexMapper.rankByBrowseTimesPT();
            List<Map<String, Object>> zf = homeIndexMapper.rankByBrowseTimesZF();
            Map<String,Object> m = new LinkedHashMap<>();
            m.put("PT",pt);
            m.put("ZF",zf);
            return Result.ok(m,"查询成功");
        }catch (Exception e){
            logger.error("数据查询异常",e);
            return Result.error("查询异常");
        }
    }

    /**
     * @Author ysj闫世杰
     * @Description 内存
     * @Date 2023/6/28 9:56
     * @Param:
     * @return com.lingxu.base.common.api.vo.Result
     **/
    @Override
    public Result findMemory() {
        try {
            SystemInfo systemInfo = new SystemInfo();
            GlobalMemory memory = systemInfo.getHardware().getMemory();
            long totalByte = memory.getTotal();
            long acaliableByte = memory.getAvailable();
            String bl = new DecimalFormat("#.##%").format((totalByte-acaliableByte)*1.0/totalByte);
            logger.info("内存大小 = {},内存使用率 ={}",formatByte(totalByte), bl);
            Map<String,Object> map = new HashMap<>();
            map.put("count",totalByte);
            map.put("use",(totalByte-acaliableByte));
            map.put("not",acaliableByte);
            map.put("countzw",formatByte(totalByte));
            map.put("usebl",bl);
            return Result.ok(map,"查询成功");
        }catch (Exception e){
            logger.error("数据查询异常",e);
            return Result.error("查询异常");
        }
    }

    /**
     * @Author ysj闫世杰
     * @Description CPU
     * @Date 2023/6/28 9:56
     * @Param:
     * @return com.lingxu.base.common.api.vo.Result
     **/
    @Override
    public Result findCPU() {
        try {
            CpuInfo cpuInfo = OshiUtil.getCpuInfo();
            Integer cpuNum = cpuInfo.getCpuNum();
            double free = cpuInfo.getFree();
            DecimalFormat format = new DecimalFormat("#.00");
            Map<String,Object> map = new HashMap<>();
            map.put("cpuNum",cpuNum);
            map.put("free",free);
            map.put("cpuUsed",Double.parseDouble(format.format(100.0D - free)));
            return Result.ok(map,"查询成功");
        }catch (Exception e){
            logger.error("数据查询异常",e);
            return Result.error("查询异常");
        }
    }

    /**
     * @Author ysj闫世杰
     * @Description 磁盘
     * @Date 2023/6/28 9:56
     * @Param:
     * @return com.lingxu.base.common.api.vo.Result
     **/
    @Override
    public Result findDisk() {
        try {
            File win = new File("/");
            Map<String,Object> map = new HashMap<>();
            if (win.exists()) {
                long total = win.getTotalSpace();
                long freeSpace = win.getFreeSpace();
                map.put("count",total/1024/1024/1024);
                map.put("free",freeSpace/1024/1024/1024);
                map.put("used",(total - freeSpace)/1024/1024/1024);
            }
            return Result.ok(map,"查询成功");
        }catch (Exception e){
            logger.error("数据查询异常",e);
            return Result.error("查询异常");
        }
    }


    private static String formatByte(long byteNumber){
        double FORMAT = 1024.0;
        double kbNumber = byteNumber/FORMAT;
        if(kbNumber<FORMAT){
            return new DecimalFormat("#.##KB").format(kbNumber);
        }
        double mbNumber = kbNumber/FORMAT;
        if(mbNumber<FORMAT){
            return new DecimalFormat("#.##MB").format(mbNumber);
        }
        double gbNumber = mbNumber/FORMAT;
        if(gbNumber<FORMAT){
            return new DecimalFormat("#.##GB").format(gbNumber);
        }
        double tbNumber = gbNumber/FORMAT;
        return new DecimalFormat("#.##TB").format(tbNumber);
    }


    /**
     * @Author ysj闫世杰
     * @Description 按使用量查询模型使用排行
     * @Date 2023/7/27 11:20
     * @Param: dto
     * @return com.lingxu.base.common.api.vo.Result
     **/
    @Override
    public Result findModelUseLimit(ParamsDTO dto) {
        try {
            if("320800".equals(dto.getAreaCode())){
                dto.setAreaCode(null);
            }
            List<Map> data = homeIndexMapper.findModelUseLimit(dto);
            return Result.ok(data,"查询成功");
        }catch (Exception e){
            logger.error("数据查询异常",e);
            return Result.error("查询异常");
        }
    }

    /**
     * @Author ysj闫世杰
     * @Description 按照问题量查询模型使用情况
     * @Date 2023/7/27 14:06
     * @Param: dto
     * @return com.lingxu.base.common.api.vo.Result
     **/
    @Override
    public Result findModelProblemLimit(ParamsDTO dto) {
        try {
            if("320800".equals(dto.getAreaCode())){
                dto.setAreaCode(null);
            }
            List<Map> data = homeIndexMapper.findModelProblemLimit(dto);
            return Result.ok(data,"查询成功");
        }catch (Exception e){
            logger.error("数据查询异常",e);
            return Result.error("查询异常");
        }
    }

    /**
     * @Author ysj闫世杰
     * @Description 统计数据量
     * @Date 2023/7/27 16:54 
     * @Param: dto
     * @return com.lingxu.base.common.api.vo.Result
     **/
    @Override
    public Result findNumberData(ParamsDTO dto) {
        try {
            if("320800".equals(dto.getAreaCode())){
                dto.setAreaCode(null);
            }
            List<Map> data = homeIndexMapper.findNumberData(dto);
            return Result.ok(data,"查询成功");
        }catch (Exception e){
            logger.error("数据查询异常",e);
            return Result.error("查询异常");
        }
    }

    /**
     * @Author ysj闫世杰
     * @Description 部门分布
     * @Date 2023/7/28 9:06
     * @Param: dto
     * @return com.lingxu.base.common.api.vo.Result
     **/
    @Override
    public Result findDeptCount(ParamsDTO dto) {
        try {
            if("320800".equals(dto.getAreaCode())){
                dto.setAreaCode(null);
            }
            List<Map> data = homeIndexMapper.findDeptCount(dto);
            return Result.ok(data,"查询成功");
        }catch (Exception e){
            logger.error("数据查询异常",e);
            return Result.error("查询异常");
        }
    }

    /**
     * @Author ysj闫世杰
     * @Description 问题量统计
     * @Date 2023/7/28 9:18
     * @Param: dto
     * @return com.lingxu.base.common.api.vo.Result
     **/
    @Override
    public Result findModelProblemCount(ParamsDTO dto) {
        try {
            if("320800".equals(dto.getAreaCode())){
                dto.setAreaCode(null);
            }
            List<Map> data = homeIndexMapper.findModelProblemCount(dto);
            return Result.ok(data,"查询成功");
        }catch (Exception e){
            logger.error("操作异常",e);
            return Result.error("操作异常");
        }
    }


    @Override
    public Result findLoginCountByArea(ParamsDTO dto) {
        try {
            if("320800".equals(dto.getAreaCode())){
                dto.setAreaCode(null);
            }
            List<Map> data = homeIndexMapper.findLoginCountByArea(dto);
            return Result.ok(data,"查询成功");
        }catch (Exception e){
            logger.error("数据查询异常",e);
            return Result.error("查询异常");
        }
    }

    //部门登录情况
    @Override
    public Result findLoginByUserDept(ParamsDTO dto) {
        try {
            if("320800".equals(dto.getAreaCode())){
                dto.setAreaCode(null);
            }
            List<Map> data = homeIndexMapper.findLoginByUserDept(dto);
            return Result.ok(data,"查询成功");
        }catch (Exception e){
            logger.error("数据查询异常",e);
            return Result.error("查询异常");
        }
    }


    //地图数据量
    @Override
    public Result findDataCountMaps(ParamsDTO dto) {
        try {
            List<Map> data = homeIndexMapper.findDataCountMaps(dto);
            return Result.ok(data,"查询成功");
        }catch (Exception e){
            logger.error("操作异常",e);
            return Result.error("操作异常");
        }
    }


    @Override
    public void findModelDataExcel(HttpServletResponse response) {
        try {
            Set<ModelIDS> modelIDSSet = homeIndexMapper.findModelIds();
            List<ModelData> list = new ArrayList<>();
            for(ModelIDS m : modelIDSSet){
                String mastermodelid = m.getMASTERMODELID();
                List<String> linkModelIds = Arrays.asList(m.getMASTERMODELID().split(","));
                ModelData modelData = homeIndexMapper.findModelData(mastermodelid,linkModelIds);
                list.add(modelData);
            }
            EasyExcelUtils.exportExcel(list,"模型结果","模型结果",ModelData.class,"模型结果.xls",response);
        }catch (Exception e){
            logger.error("数据查询异常",e);
        }
    }

    @Override
    public Result findModelCloneLimit(ParamsDTO dto) {
        try {
            return Result.ok(homeIndexMapper.findModelCloneLimit(dto),"查询成功");
        }catch (Exception e){
            logger.error("数据查询异常",e);
            return Result.error("查询异常");
        }
    }


    @Override
    public Result findAreaModelRun(ParamsDTO dto) {
        try {
            return Result.ok(homeIndexMapper.findAreaModelRun(dto),"查询成功");
        }catch (Exception e){
            logger.error("数据查询异常",e);
            return Result.error("查询异常");
        }
    }


    @Override
    public Result findResultFeedBack(ParamsDTO dto) {
        try {
            //查询模型分类
            List<Map> data = new ArrayList<>();
            List<NumTypeVO> modelTypes = homeIndexMapper.findModelTypes(dto);
            for(NumTypeVO vo : modelTypes){
                Map<String,Object> map = new HashMap<>();
                map.put("NAME",vo.getType());
                map.put("CODE",vo.getCode());
                List<String> masterId = homeIndexMapper.findMasterModelId(vo.getCode(),dto);
                //查询各个反馈分类
                List<Map> resultList = homeIndexMapper.findResultFeedBack(masterId);
                map.put("RESULT",resultList);
                data.add(map);
            }
            return Result.ok(data,"查询成功");
        }catch (Exception e){
            logger.error("数据查询异常",e);
            return Result.error("查询异常");
        }
    }



    @Override
    public Result findModel(ParamsDTO dto) {
        try {
            List<Map> data = homeIndexMapper.findModel(dto);
            return Result.ok(data,"查询成功");
        }catch (Exception e){
            logger.error("数据查询异常",e);
            return Result.error("查询异常");
        }
    }
}
